/* Copyright Andy Mitchell 2007. No warranties */

function FilterPopupUI(gtdinboxPage, name, type, elParentPopuper, parentNames, parentTypes, parentSearch, filterParent){
try{
	this._gtdinboxPage = gtdinboxPage;
	this._doc = gtdinboxPage.doc;
	this._labels = gtdinboxPage._labels;
	this._parentNames = parentNames || [];
	this._parentTypes = parentTypes || [type];
	this._parentSearch = parentSearch || "";
	if( name instanceof Array ){	// contact, [name,email]
		this._name = name[0];
		this._email = name[1] || name[0];
	}else{
		this._name = name;
	}
	this._type = type;
	this._elParentPopuper = elParentPopuper;
	this._sp = gtdinboxPage.sp;
	this._filterParent = filterParent;
	if( filterParent ){
		this._filterParent.highlighted(false);
	}
	
	this._eventObservers = new EventObservers(this);
	this._showHiders = [];
	
	this._create();
	this._eventObservers.observe( this.el, "click", this.mouseDown, true);
	this._eventObservers.observe( this.el, "contextmenu", this.contextMenu, true);
	
	this.highlighted(true);
	this.addPopupChildObject( this );
	
	return this;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI construct\n" + e.toString());
}
};

FilterPopupUI.prototype._create = function(){
try{
	this.el = this._doc.createElement("DIV");
		this.el.className = "filter-popup";
	var doc = this._gtdinboxPage.gmailDOM.element("document");
	if( doc ) doc.body.appendChild( this.el );
	
	var elTitle = this._doc.createElement("DIV");
		elTitle.className = "title";
		if( this._parentNames.length > 0 ){
			elTitle.innerHTML = "<div class='path'>" + this._parentNames.join(", ") + "</div>";
		}
		elTitle.innerHTML += (this._name || this._email || "");
	this.el.appendChild( elTitle );
	var elClose = this._doc.createElement("IMG");
		elClose.src = "chrome://gtdinbox/content/cross.png";
		elClose.className = "close-button";
		elClose.style.position = "absolute";
		elClose.style.right = "0px";
		elClose.style.top = "0px";
		this._eventObservers.observe(elClose, "mousedown", this.clickClose, false);
	elTitle.appendChild(elClose);
	
	this._popuper = new Popuper(this._gtdinboxPage, this.el, this);
	this._popuper.addEventHandler( this, "popupOff", this.onPopupOff );	
	
	this._createLink(this.el, "Show All", "");
	
	switch( this._type ){
		case "Statuses":
			// Show Personal
			this._createLink(this.el, "Sent To Self", GIPROTOTYPE.restrictSearchToUser(this._gtdinboxPage._environment.emails) );	// TODO language
			
			// Review
			var d = (new Date()).valueOf();
			var day = 1000*60*60*24;
			var elReviews = this._doc.createElement("DIV");
			this._createLink( elReviews, "Over One Week Old", "before:" + GIPROTOTYPE.searchDate(d-(day*7)) );		// TODO language
			this._createLink( elReviews, "Over One Month Old", "before:" + GIPROTOTYPE.searchDate(d-(day*31)) );	// TODO language
			this._createLink( elReviews, "Over Three Months Old", "before:" + GIPROTOTYPE.searchDate(d-(day*66)) );	// TODO language
			this._createBreak();
			this._createSection("Review", elReviews);	// TODO language
			
			break;
		case "Projects":
			this._createStatuses();
			if(!this._hasParentType("Contexts")) this._createLabelsSection("Contexts");
			if(!this._hasParentType("Contexts")) this._createLabelsSection("References");
			this._createContactsSectionByLabel();
			this._createBreak();
			this._createLink(this.el, "Associated Files", "has:attachment");	// TODO language
			break;
		case "Contexts":
			this._createStatuses();
			if(!this._hasParentType("Contexts")) this._createLabelsSection("Projects");
			if(!this._hasParentType("Contexts")) this._createLabelsSection("References");
			this._createContactsSectionByLabel();
			this._createBreak();
			this._createLink(this.el, "Associated Files", "has:attachment");	// TODO language
			break;
		case "References":
			// Show Personal
			this._createLink(this.el, "Sent To Self", GIPROTOTYPE.restrictSearchToUser(this._gtdinboxPage._environment.emails) );	// TODO language
			if(!this._hasParentType("Contexts")) this._createLabelsSection("Contexts");
			if(!this._hasParentType("Contexts")) this._createLabelsSection("Projects");
			this._createBreak();
			this._createLink(this.el, "Associated Files", "has:attachment");	// TODO language
			break;
		case "Misc":
			this._createStatuses();
			this._createLink(this.el, "Associated Files", "has:attachment");	// TODO language
			break;
		case "Old":
			break;
		case "Contact":
			this._createBreak();
			
			this._createLink(this.el, "Compose To " + (this._email || this._name), "special.compose:" + (this._email || this._name), null, null, false, true );
			
			this._createStatuses();
			this._createLabelsSection("Contexts", true);
			this._createLabelsSection("Projects", true);
			this._createLabelsSection("References", true);
			this._createLink(this.el, "Associated Files", "has:attachment");	// TODO language
			break;
	}
	
	// Search
	this._createBreak();
	var elSearch = this._doc.createElement("DIV");
		elSearch.className = "search";
	var elSearchInput = this._doc.createElement("INPUT");
		elSearchInput.setAttribute("type", "text");
	elSearch.appendChild( elSearchInput );
	var elSearchCmd = this._doc.createElement("BUTTON");
		elSearchCmd.innerHTML = "Search";	// TODO language
	elSearch.appendChild( elSearchCmd );
	this._createSection("Search Over", elSearch );	// TODO language
	
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI create\n" + e.toString());
}
};
FilterPopupUI.prototype._hasParentType = function(type){
	for( var i = 0; i < this._parentTypes.length; i++ ){
		if( this._parentTypes[i]==type ){
			return true;
		}
	}
	return false;
};
FilterPopupUI.prototype._createBreak = function(elParent){
	if( !elParent ) elParent = this.el;
	
	var elBreak = this._doc.createElement("DIV");
		elBreak.className = "break";
	elBreak.innerHTML = "&nbsp;";
	
	elParent.appendChild( elBreak );
	
	return elBreak;
};
FilterPopupUI.prototype._createLink = function(elParent, title, search, name, type, canExpand, excludeParentSearch){
try{	
	if( !excludeParentSearch ) search = this._parentSearch + " " + search;

	var elLink = this._doc.createElement("DIV");
		elLink.className = "link";
	if( elParent ) elParent.appendChild( elLink );
	
	var elBody = this._doc.createElement("DIV");
		elBody.className = "body";
		elBody.innerHTML = title;
	elLink.appendChild( elBody );
	
	var fAttribs = function(el){
		el.setAttribute("gtdSearch", search);
		if( name ) el.setAttribute("gtdName", name);
		if( type ) el.setAttribute("gtdType", type);
	};
	fAttribs(elLink);
	fAttribs(elBody);
	
	if( name && canExpand ){
		var elExpander = this._doc.createElement("IMG");
			elExpander.className = "expander";
			elExpander.src = "chrome://gtdinbox/content/filter-extend.png";
		elLink.appendChild( elExpander );
		fAttribs(elExpander);
	}
	
	var elClear = this._doc.createElement("DIV");
		elClear.style.clear = "both";
		elClear.style.height = "1px";
	elLink.appendChild( elClear );
	
	return elLink;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createLink\n" + e.toString());
}
};
FilterPopupUI.prototype._createSection = function(title, elContent, elParent){
try{
	elParent = elParent || this.el;
	var showHider = new Showhider(this._gtdinboxPage, "filter-" + title, {doc: this._doc, 'elParent':elParent, 'title':title, 'elContent': elContent});
	this._showHiders.push(showHider);
	return showHider;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createSection\n" + e.toString());
}
};
FilterPopupUI.prototype._createStatuses = function(){
try{
	this._createBreak();
	
	// Create set of links for statuses
	var labels = GIPROTOTYPE.clone(this._labels.getLabelsArray("Statuses"));
	
	var settings = this._gtdinboxPage.gtdinboxBrowser.settings.labels.types.Statuses;
	for( d in settings.defaults ){
		var label = settings.prefix + settings.defaults[d];
		
		for( var i = 0; i < labels.length; i++ ){
			if( labels[i]==label ){
				this._createLink( this.el, label.replace(settings.prefix,""), GIPROTOTYPE.searchableLabel(label), label, "Statuses", true);
				labels.splice(i,1);
				i--;
			}
		}
	}
	// And the rest:
	for( var i = 0; i < labels.length; i++ ){
		var label = labels[i];
		this._createLink( this.el, label.replace(settings.prefix,""), GIPROTOTYPE.searchableLabel(label), label, "Statuses", true);
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createStatuses\n" + e.toString());
}
};
FilterPopupUI.prototype._createLabelsSection = function(type, isContact){
	// Get set of prioritised labels for this label; and all labels; then create box
try{
	this._createBreak();
	
	var settings = this._gtdinboxPage.gtdinboxBrowser.settings.labels.types[type];
	var labelsHash = GIPROTOTYPE.clone(this._labels.getLabelsHash(type));
	
	var foundOne = false;
	// Grab related ones first:
	var related = null;
	if( isContact ){
		var related = this._sp.getRankedLabelsByContact(settings.prefix, (this._email || this._name) );
	}else{
		var related = this._sp.getRankedLabelsByLabel(settings.prefix, this._name);
	}
	var elRelated = this._doc.createElement("DIV");
	for( var i = 0; i < related.length; i++ ){
		var label = related[i];
		this._createLink( elRelated, label.replace(settings.prefix,""), GIPROTOTYPE.searchableLabel(label), label, type, true);
		if( labelsHash[label] ) delete labelsHash[label];
		foundOne = true;
	}
	// And process the rest
	var elMore = this._doc.createElement("DIV");
	for( label in labelsHash ){
		this._createLink( elMore, label.replace(settings.prefix,""), GIPROTOTYPE.searchableLabel(label), label, type, true);
		foundOne = true;
	}
	
	if( foundOne ){
		var showHider = this._createSection("All", elMore, elRelated);	// TODO language
		this._createSection(type, elRelated);	// TODO language on type		
		
		if( related.length==0 ) showHider.show(true);
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createLabelsSection\n" + e.toString());
}
};
FilterPopupUI.prototype._createContactsSectionByLabel = function(){
	// Find all contacts associated with this name
try{
	// Grab related ones first:
	var related = this._sp.getRankedContactsByLabel(this._name);
	if( related.length > 0 ){
		var elRelated = this._doc.createElement("DIV");
		for( var i = 0; i < related.length; i++ ){
			var contact = related[i];
			this._createLink( elRelated, contact, GIPROTOTYPE.restrictSearchToUser(contact, true), contact, "Contact", true);
		}
		this._createLink(elRelated, "Compose to All", "special.compose:" + related.join(", "), null, null, false, true);	// TODO language
		this._createSection("Contacts", elRelated);	// TODO language
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createContactsSectionByLabel\n" + e.toString());
}
};

FilterPopupUI.prototype.contextMenu = function(event){
	this._gtdinboxPage.unsafeWindow.console.log("start gtg");
	var el = GIPROTOTYPE.element(event);
	if( el.getAttribute("gtdName") ){
		this._gtdinboxPage.unsafeWindow.console.log("gtg");
		GIPROTOTYPE.stop(event);
		this.clickExtend(el);
	}
};
FilterPopupUI.prototype.mouseDown = function(event){
	
	try{
		var el = GIPROTOTYPE.element(event);
		if( event.button==2 ) return;
		if( event.shiftKey ){	// async
			this.forceOff();
			return;
		}
		
		// Detect the type (search button, extend button, regular filter)
		if( el.nodeName=="BUTTON" ){	// search
			el = el.parentNode.getElementsByTagName("INPUT")[0];
			this._gtdinboxPage.search( this._parentSearch + " " + el.value );
			GIPROTOTYPE.stop(event);
			this.forceOff();
		}else if( el.nodeName=="IMG" && el.getAttribute("gtdName") ){	// extend
			this.clickExtend(el);
			GIPROTOTYPE.stop(event);
		}else if( el.getAttribute("gtdSearch") ){
			var search = el.getAttribute("gtdSearch");
			this._gtdinboxPage.unsafeWindow.console.log(search);
			if( search.indexOf("special.compose:")==0 ){
				this._gtdinboxPage.unsafeWindow.console.log(search.replace("special.compose:", ""));
				this._gtdinboxPage._composeUI.clickComposeTo( search.replace("special.compose:", "") );
			}else{
				this._gtdinboxPage.search( (search||"") );
			}
			GIPROTOTYPE.stop(event);
			this.forceOff();
		}
	}catch(e){
		if( GTDDEBUGMODE ) alert("filterpopup mouseDown\n" + e.toString());
	}
};
FilterPopupUI.prototype.clickExtend = function(el){
	// Use the line-item to generate new popup
try{
	if( this._filterChild ){	// turn off
		this._filterChild.destroy();
		this._filterChild = null;
		if( this._filterChildEl==el ) return;
	}
	var name = el.getAttribute("gtdName");
	var type = el.getAttribute("gtdType");
	var parentSearch = this._parentSearch + " " + (el.getAttribute("gtdSearch")||"");
	var parentTypes = this._parentTypes.concat( this._type );
	var parentNames = this._parentNames.concat( this._name );
	this._filterChild = new FilterPopupUI( this._gtdinboxPage, name, type, el, parentNames, parentTypes, parentSearch, this );
	this._filterChild.popup(el,{location:'right'});
	this._filterChildEl = el;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI clickExtend\n" + e.toString());
}
};

FilterPopupUI.prototype.addPopupChildObject = function(popupObj){
	// Add to this popuper as 'safe', and propogate up
	this._popuper.addPopupChild( popupObj );
	if( this._filterParent ) this._filterParent.addPopupChildObject( popupObj );
};

FilterPopupUI.prototype.highlighted = function(v){
	if( typeof v=="undefined" ) return GIPROTOTYPE.hasClassName(this.el, "filter-highlighted");
	if( v ){
		GIPROTOTYPE.addClassName(this.el, "filter-highlighted");
	}else{
		GIPROTOTYPE.removeClassName( this.el, "filter-highlighted");
	}
};

FilterPopupUI.prototype.forceOff = function(){
	// Find highest FilterPopupUI in chain; and destroy it
	var fp = this;
	while( fp._filterParent ) fp = fp._filterParent;
	fp.destroy();
};
FilterPopupUI.prototype.onPopupOff = function(){
	this.destroy();
};
FilterPopupUI.prototype.clickClose = function(){
	this.destroy();
}
FilterPopupUI.prototype.destroy = function(){
try{
	if( !this.el ) return;	// already destroyed
	
	/*
	var doc = this.el.ownerDocument;
	var elFooter = this._gtdinboxPage.gmailDOM.element("FooterElement");
	var gtd = this._gtdinboxPage;
	setTimeout( GIPROTOTYPE.bind(this, function(){
		GIPROTOTYPE.doMouseEvent(elFooter.ownerDocument, elFooter, "mousedown", 0, 1, 1);
		GIPROTOTYPE.doMouseEvent(elFooter.ownerDocument, elFooter, "click", 0, 2, 2);
		gtd.unsafeWindow.console.log("clicked out");
		}), 3000 );
	*/
	
	if( this._filterParent ) this._filterParent.highlighted(true);
	
	if( this._filterChild ){	// turn off
		this._filterChild.destroy();
	}
	
	if( this.popupOff ) this.popupOff();
	if( this._popuper ) this._popuper.destroy();
	this._eventObservers.destroy();
	
	for( var i = 0; i < this._showHiders.length; i++ ){
		this._showHiders[i].destroy();
	}
	
	this._gtdinboxPage = null;
	this._doc = null;
	
	if( this.el && this.el.parentNode ) this.el.parentNode.removeChild(this.el);
	this.el = null;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI destroy\n" + e.toString());
}
};















/*


function FilterPopupUI(gtdinboxPage, parentPopup){
	this._eventObservers = new EventObservers(this);
	this._gtdinboxPage = gtdinboxPage;
	this._doc = gtdinboxPage.doc;
	this._settings = gtdinboxPage.gtdinboxBrowser.settings;
	this._labels = gtdinboxPage._labels;
	this._parentPopup = parentPopup;
	
	return this;
}

FilterPopupUI.prototype.create = function(elParent, parentSearch, showBasic, showPersonal, inlineTypes, extendTypes){
try{

	this.el = this._doc.createElement("DIV");
		this.el.className = "filter-popup";
	if( elParent ) elParent.appendChild( this.el );
	
	var elClose = this._doc.createElement("IMG");
		elClose.src = "chrome://gtdinbox/content/cross.png";
		elClose.className = "close-button";
		elClose.style.position = "absolute";
		elClose.style.right = "0px";
		elClose.style.top = "0px";
		this._eventObservers.observe(elClose, "mousedown", this.clickClose, false);
	this.el.appendChild(elClose);
	
	var fCreateLineItem = GIPROTOTYPE.bind(this, function(type, search, className, canExtend, innerText, insertBefore){
		var prefix = type? this._settings.labels.types[ type ].prefix : "";
		var el = this._doc.createElement("DIV");
			el.className = "line-item " + (className||"");
		el.innerHTML = innerText;
		if( search ) el.setAttribute("gtdSearch", search);
		el.setAttribute("gtdParentSearch", parentSearch);
		el.setAttribute("gtdShowPersonal", (showPersonal? "1":"") );
		if( type ) el.setAttribute("gtdLabelType", type);
		if( canExtend ){
			el.innerHTML += "<img src='chrome://gtdinbox/content/filter-extend.png' />";
		}
		if( insertBefore ) this.el.insertBefore(el, insertBefore);
		else this.el.appendChild( el )
	});
	var fCreateBreak = GIPROTOTYPE.bind(this, function(insertBefore){
		var el = this._doc.createElement("DIV");
			el.className = "line-break";
		if( insertBefore ) this.el.insertBefore(el, insertBefore);
		else this.el.appendChild( el )
	});
	
	
	if( inlineTypes && inlineTypes.length>0 ){	// Show these types inline
		for( var i = 0; i < inlineTypes.length; i++ ){
			var labels = GIPROTOTYPE.clone(this._labels.getLabelsArray( inlineTypes[i] ));
			if( labels ){
				var prefix = this._settings.labels.types[inlineTypes[i]].prefix;
				if( this._settings.labels.types[inlineTypes[i]].defaults ){	// Re-organise - not very efficient
					var defaults = this._settings.labels.types[inlineTypes[i]].defaults;
					var newlabels = [];
					for( d in defaults ){
						
						for( var j = labels.length - 1; j>=0; j-- ){
							if( labels[j]==(prefix+defaults[d]) ){
								newlabels.push( labels[j] );
								labels.splice(j, 1);
							}
						}
					}
					labels = newlabels.concat(labels);
				}
				if( labels ){
					for( var j = 0; j < labels.length; j++ ){
						fCreateLineItem(inlineTypes[i], GIPROTOTYPE.searchableLabel(labels[j]), "line-item-inline", true, labels[j].replace(prefix,"") );
					}
					fCreateBreak();
				}
			}
		}
	};
	
	if( extendTypes && extendTypes.length>0 ){	// Show these types inline
		for( var i = 0; i < extendTypes.length; i++ ){
			fCreateLineItem(extendTypes[i], null, "line-item-extend", true, "By " + extendTypes[i]);	// TODO language
			fCreateBreak();
		}
	};
	
	if( showBasic || showPersonal ) fCreateBreak(this.el.firstChild);
	if( showBasic ){	// Show 'View' (insert first) and SearchBox (append last)

		if( showPersonal ){
			fCreateLineItem(null, GIPROTOTYPE.restrictSearchToUser(this._gtdinboxPage._environment.emails), null, null, "Show Personal (From Me)", this.el.firstChild);	// TODO language
		}	

		fCreateLineItem(null, null, null, null, "Show All", this.el.firstChild);	// TODO language
		
		var el = this._doc.createElement("DIV");
			el.className = "search";
			
		el.setAttribute("gtdParentSearch", parentSearch);
		el.innerHTML = "<input type='text' /><button class='filter-search' gtdParentSearchForSearch=\"" + parentSearch.replace(/\"/g, "\\\"") + "\">Search</button>"	// TODO language
		this.el.appendChild(el);
	}
	
	this._parentSearch = parentSearch;
	this._eventObservers.observe( this.el, "mouseup", this.mouseDown, false);
}catch(e){
	if( GTDDEBUGMODE ) alert("filterpopup create\n" + e.toString());
}
	this._popuper = new Popuper(this._gtdinboxPage, this.el, this);
	this._popuper.addEventHandler( this, "popupOff", this.onPopupOff );
	return this;
};

FilterPopupUI.prototype.mouseDown = function(event){
try{
	if( event.button==2 ) return;
	if( event.shiftKey ){	// async
		this.forceOff();
		return;
	}

	// Detect the type (search button, extend button, regular filter)
	var el = GIPROTOTYPE.element(event);
	if( el.nodeName=="BUTTON" ){	// search
		this.clickSearch(el.parentNode.getElementsByTagName("INPUT")[0]);
	}else if( el.nodeName=="IMG" ){	// extend
		this.clickExtend(el.parentNode);
	}else if( el.className.indexOf("line-item")>-1 ){
		this.clickFilter(el);
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("filterpopup mouseDown\n" + e.toString());
}
};


FilterPopupUI.prototype.clickFilter = function(el){
try{
	// Use the line-item to do new search
	this._gtdinboxPage.search( this._parentSearch + " " + (el.getAttribute("gtdSearch")||"") );
	this.forceOff();
}catch(e){
	if( GTDDEBUGMODE ) alert("filterpopup click filter\n" + e.toString());
}
};

FilterPopupUI.prototype.clickExtend = function(el){
	// Use the line-item to generate new popup
	
	if( this._filterChild ){	// turn off
		this._filterChild.destroy();
		this._filterChild = null;
		if( this._filterChildEl==el ) return;
	}
	var parentSearch = this._parentSearch + " " + (el.getAttribute("gtdSearch")||"");
	var extender = (el.className.indexOf("line-item-extend")>-1);
	var showBasic = extender? false:true;
	var showPersonal = (el.getAttribute("gtdShowPersonal")=="1")? true:false;
	var inlineTypes = extender? [el.getAttribute("gtdLabelType")]:[];
	this._filterChild = new FilterPopupUI( this._gtdinboxPage, this ).create(el.ownerDocument.body, parentSearch, showBasic, showPersonal, inlineTypes);
	this._filterChild.popup(el,{location:'right'});
	this._filterChildEl = el;
	this._popuper.addPopupChild(this._filterChild);
};

FilterPopupUI.prototype.clickSearch = function(el){
	// Use the input box to fire a search
	this._gtdinboxPage.search( this._parentSearch + " " + el.value );
	this.forceOff();
};


FilterPopupUI.prototype.forceOff = function(){
	// Find highest FilterPopupUI in chain; and destroy it
	var fp = this;
	while( fp._parentPopup ) fp = fp._parentPopup;
	fp.destroy();
};
FilterPopupUI.prototype.onPopupOff = function(){
	this.destroy();
};
FilterPopupUI.prototype.clickClose = function(){
	this.destroy();
}
FilterPopupUI.prototype.destroy = function(){
	if( !this.el ) return;	// already destroyed
	
	if( this.popupOff ) this.popupOff();
	if( this._popuper ) this._popuper.destroy();
	this._eventObservers.destroy();
	
	if( this.el ) this.el.parentNode.removeChild(this.el);
	this.el = null;
};
*/